<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>资金管理</el-breadcrumb-item>
      <el-breadcrumb-item>其它资金确认</el-breadcrumb-item>
      <el-breadcrumb-item>历史申请信息</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 卡片视图区域 -->
      <el-button plain icon="el-icon-back" style='margin-bottom: 15px;font-size: 16px;' @click='$router.go(-1)'>返回</el-button>
      <div class="clearfix">
        <el-row type='flex' align='middle' justify='left'>
          <el-col style='display: flex!important;align-items: center!important;' :span="3">
            <h3>筛选查询</h3>
          </el-col>
          <el-col>
            <el-row type='flex' justify='space-around'>
              <el-date-picker
                v-model="date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="截止日期">
              </el-date-picker>

              <el-select v-model="queryInfo.sqtype" placeholder="类型">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>

              <el-select v-model="queryInfo.sqstatus" placeholder="状态">
                <el-option
                  v-for="item in stateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-row>
          </el-col>
          <el-col :span="3"><el-button type="primary" size="small" icon="el-icon-search" @click='search'>查询结果</el-button></el-col>
          <el-col :span="3"><el-button type="danger" size="small" @click='clearSearch'>清空筛选</el-button></el-col>
        </el-row>
      </div>
      <h3>查询结果</h3>
      <!-- table表格区域 -->
      <el-table :data="historyList" border stripe :header-cell-style="{background:'#eee',color:'#606266',fontSize: '14px'}">
        <el-table-column type="index" align="center"></el-table-column>
        <el-table-column label="单位名称" prop="dwmc" align="center" width='200'></el-table-column>
        <el-table-column label="单位账号" prop="gjjzh" width="80px" align="center"></el-table-column>
        <el-table-column label="录入人" prop="lxr" width="100px" align="center"></el-table-column>
        <el-table-column label="联系电话" prop="lxdh" width="150px" align="center"></el-table-column>
        <el-table-column label="拒绝原因" prop="jjcontent" align="center" width='200'></el-table-column>
        <el-table-column label="总流水号" prop="lsh" align="center"></el-table-column>
        <el-table-column label="本年号" prop="num" width="100px" align="center"></el-table-column>
        <el-table-column label="申请日期" prop="sqrq" width="200px" align="center"></el-table-column>
        <el-table-column label="申请状态" prop="sqstatus" align="center"></el-table-column>
        <el-table-column label="申请类型" prop="sqtype" align="center"></el-table-column>
        <el-table-column label="确认资金金额" prop="zjje" align="center" width='150'></el-table-column>
        <el-table-column  label="操作" align="center" fixed='right' width='150'>
          <template v-slot="{row}">
            <el-button v-if="row.sqstatus == '申请'" :key='1' disabled type="success" icon="el-icon-check" size="mini" @click='test'>申请中...</el-button>
            <el-button  v-else-if="row.sqstatus == '同意打印凭证'"  :key='2' type="primary" icon="el-icon-view" size="mini" @click="downloadPdf(row)">下载凭证</el-button>
            <el-button  v-else-if="row.sqstatus == '驳回'" type="warning" :key='3' icon="el-icon-edit" size="mini" @click="editApply(row)">修改申请</el-button>
            <el-button v-else disabled type="danger"  :key='4' icon="el-icon-close" size="mini">拒绝申请</el-button>
<!--            <el-button v-show="row.sqstatus == '申请'" disabled type="success" icon="el-icon-check" size="mini" @click='test'>申请中...</el-button>-->
<!--            <el-button  v-show="row.sqstatus == '同意打印凭证'"  type="primary" icon="el-icon-view" size="mini" @click="downloadPdf(row)">下载凭证</el-button>-->
<!--            <el-button  v-show="row.sqstatus == '驳回'" type="warning" icon="el-icon-edit" size="mini" @click="editApply(row)">修改申请</el-button>-->
<!--            <el-button v-show="row.sqstatus == '拒绝'" disabled type="danger" icon="el-icon-close" size="mini">拒绝申请</el-button>-->
          </template>
        </el-table-column>1
<!--          <template slot-scope="scope">-->
<!--            {{scope.row.add_time | dateFormat}}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="操作" width="130px">-->
<!--          <template slot-scope="scope">-->
<!--            <el-button type="primary" icon="el-icon-edit" size="mini"></el-button>-->
<!--            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeById(scope.row.goods_id)"></el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pageNum" :page-sizes="[5, 10, 15, 20]" :page-size="queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" background>
      </el-pagination>
    </el-card>

    <!--  修改申请弹窗  -->
    <el-dialog title="申请信息修改" :visible.sync="editDialogVisible" width="60%" @close="btnCancel">
      <h1>基本信息修改</h1>
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="120px">
        <el-form-item label="申请金额:" prop="zjje">
          <el-input v-model="editForm.zjje"></el-input>
        </el-form-item>
        <el-form-item label="录入人:" prop="lxr">
          <el-input v-model='editForm.lxr'></el-input>
        </el-form-item>
        <el-form-item label="联系电话:" prop="lxdh">
          <el-input v-model='editForm.lxdh'></el-input>
        </el-form-item>
      </el-form>
      <!--  文件上传    -->
      <div v-if="isUpload">
        <h1>文件上传</h1>
        <el-table :data="fileInformation.Imports" style="width: 100%" border>
          <el-table-column prop="ImportName" label="需要上传的文件" align='center'>
          </el-table-column>
          <el-table-column label="文件类型" align='center' prop="ImportType">
          </el-table-column>
          <el-table-column label="上传状态" align='center'>
            <template v-slot="{ row }">
              <el-tag v-if="row.IsUpload" type="success">已上传({{row.IsReq ? '必传' : '非必传'}})</el-tag>
              <el-tag v-else type="info">未上传({{row.IsReq ? '必传' : '非必传'}})</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align='center'>
            <template slot-scope="scope">
              <el-upload
                class="upload-demo"
                :ref="'uploadRef' + scope.$index"
                action=""
                :limit="1"
                :before-remove="beforeRemove"
                :on-exceed="handleExceed"
                :auto-upload="false">
                <el-button slot="trigger" size="small" type="text">选取文件</el-button>
                <el-button style="margin-left: 10px;" size="small" type="text" @click="submitUpload(scope.row.ImportType, scope.$index)">上传</el-button>
                <el-button size="small" type="text" @click="preview(scope.$index)">预览</el-button>
              </el-upload>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="btnOk">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 预览图片 -->
    <div class='prePic' v-show="previewIsShow" >
      <i class="el-icon-close" @click="previewIsShow = false"></i>
      <el-image
        fit='cover'
        :z-index="9999"
        style="width: 450px; height: 450px"
        :src="previewUrl"
        :preview-src-list="previewUrlList">
      </el-image>
    </div>

  </div>
</template>

<script>
import toBlob from '@/utils/toblob.js'
// 0申请中 1同意可以下载凭证 2驳回，可修改 3拒绝不可修改
export default {
  data() {
    return {
      typeOptions: [],
      stateOptions: [
        {
          value: '申请',
          label: '申请'
        },
        {
          value: '同意打印凭证',
          label: '同意打印凭证'
        },
        {
          value: '驳回',
          label: '驳回'
        },
        {
          value: '拒绝',
          label: '拒绝'
        }
      ],
      // 查询参数对象
      queryInfo: {
        gjjzh: sessionStorage.getItem('gjjzh'),
        startDate: '',
        endDate: '',
        sqstatus: '',
        sqtype: '',
        pageNum: 1, // 默认值
        pageSize: 10 // 默认值
      },
      // 申请列表
      historyList: [],
      // 总数据条数
      total: 0,
      date: '',
      // 申请信息填写
      editForm: {
        lxdh: '',
        lxr: '',
        zjje: 0
      },
      editFormRules: {
        zjje: [
          { required: true, message: '要确认的资金金额不能为空', trigger: 'blur' },
          { pattern: /^([1-9]\d{0,9}|0)(\.\d{1,2})?$/, message: '金额设置非法', trigger: 'blur' }
        ],
        lxr: [
          { required: true, message: '录入人不能为空', trigger: 'blur' }
        ],
        lxdh: [
          { required: true, message: '联系电话不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机联系方式', trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      isUpload: false, // 是否需要传文件
      fileInformation: {
        BusiName: '',
        Busiid: '',
        ChannelCode: '',
        Imports: [], // 文件列表
        SeviceCode: ''
      }, // 上传文件信息
      previewIsShow: false, // 预览显示
      previewUrlList: [], // 预览列表
      previewUrl: '' // 预览地址
    }
  },
  created() {
    this.getHistoyList()
    this.gjjzh = window.sessionStorage.getItem('gjjzh')
    this.getFundType()
  },
  methods: {
    // 查询资金类型有哪些的方法
   async getFundType() {
      const { data } = await this.$http.get('/qtzj/fetchAllZjqrlistSqtype')
     // 数组编辑
     this.typeOptions = data.data.map(item => {
       return {
         value: item,
         label: item
       }
     })
    },
    // 根据分页获取历史申请列表信息
    async getHistoyList() {
      const { data: res } = await this.$http.get('/qtzj/qureyZjqrlist', {params: this.queryInfo})
      console.log('历史申请信息',res)
      if (res.code !== 200) {
        if (res.code === 201) {
          this.historyList = []
          return this.$message.warning('查询结果为空！')
        } else {
          return this.$message.error('获取历史申请信息失败！')
        }
      }
      if (res.data.total === 0) {
        return this.$message.error('没有符合查询条件的信息！')
      }
      this.$message.success('获取历史申请信息成功！')
      this.historyList = res.data.records
      this.total = res.data.total
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getHistoyList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getHistoyList()
    },
    async search() {
      // date控件不选择时是空字符串,选择了是数组，长度为2
      // if (!this.date) return this.$message.warning('请指定查询时间范围 ！')
      if (this.date) {
        // 选择了日期才进行格式修改
        this.queryInfo.startDate = this.date[0].getFullYear() + '-' + ((this.date[0].getMonth() + 1 + '') .padStart(2, '0')) + '-' + ((this.date[0].getDate()+ '').padStart(2, '0'))
        this.queryInfo.endDate = this.date[1].getFullYear() + '-' + ((this.date[1].getMonth() + 1 + '').padStart(2, '0')) + '-' + ((this.date[1].getDate() + '').padStart(2, '0'))
      }
      this.getHistoyList()
    },
    // 清除筛选条件
    clearSearch() {
      this.date = ''
      // 初始化
     this.queryInfo =  {
        gjjzh: sessionStorage.getItem('gjjzh'),
          startDate: '',
          endDate: '',
          state: '',
          type: '',
          pageNum: 1, // 默认值
          pageSize: 10 // 默认值
      },
      this.getHistoyList()
    },
    // 下载按钮点击事件
    async downloadPdf(obj) {
      const { data: res } = await this.$http.post('/qtzj/printCertificate', obj)
      console.log('下载',res)
      // 1. 借助自己写的工具类toBlob将base64转换成Blob格式文件，并生成文件对象的前端地址
      let fileURL = window.URL.createObjectURL(toBlob(res.data, 'pdf'))
      // 新页面打开pdf文件，这个页面其实有下载按钮
      window.open(fileURL)

      // 2. 自动下载流程
      let link = document.createElement('a')  //创建一个超链接元素
      link.style.display = 'none'   // 隐藏该元素
      link.href = fileURL  // 创建下载的链接
      // ⭐ a标签 href+download 属性定义了下载链接的地址，download属性指定下载文件的名称。
      link.setAttribute('download',  '确认书'+ '.pdf')
      document.body.appendChild(link) // 插入元素
      link.click()  // 模拟点击触发download地址下载
      document.body.removeChild(link) // 下载完成移除元素
      window.URL.revokeObjectURL(fileURL) // 释放掉blob对象
    },
    async editApply(obj) {
      // obj包含当前操作对象的全部信息，表单只显示了三条可修改数据
      this.editForm = obj
      // 修改申请时，是否要上传影像材料，通过接口查询
      const { data: { data: { imageType } } } = await this.$http.get('/qtzj/queryDetailZjqrlist', { params: this.editForm })
      // imageType=不需要影像,则不需要上传文件
      if ( imageType !== '不需要影像' ) this.isUpload = true
      // 需要上传影像，获取文件信息
      const {data: { data }} = await this.$http.get('/qtzj/fetchImportList', { params: {
          applicationType: this.editForm.sqtype,
          applicationDate: this.editForm.sqrq,
          gjjzh: window.sessionStorage.getItem('gjjzh')
        }})
      // 文件列表是文件信息对象中的Imports属性
      this.fileInformation = data
      console.log(this.fileInformation)
      this.editDialogVisible = true
    },
    async btnOk() {
      // 1. 文件上传判断，必传的未传禁止提交；如果该申请不需要文件上传，那么这一步可以省略
      if (this.isUpload) {
        // 需要上传文件
        // 定义必传文件状态标记，存在在未传的则true
        let hasNoUploadState = this.fileInformation.Imports.some(item => item.IsReq && !item.IsUpload)
        if (hasNoUploadState) return this.$message.warning('必传文件未上传，请检查后上传')
      }
      // 2. 表单信息提交
      const {data: {code}} = await this.$http.post('/qtzj/modifyZjqrlist', this.editForm)
      if (code !==200) return this.$message.error('修改失败')
      this.$message.success('修改成功')
      this.editDialogVisible = false
      // 重新获取数据
      this.getHistoyList()
    },
    btnCancel() {
      this.$refs.editFormRef.resetFields()
    },
    // 上传文件
    async submitUpload(fileType,index) {
      fileType = fileType.split(',')
      console.log(index)
      // 确定要上传的是哪个文件选择器
      const ref = 'uploadRef' + index
      if (this.$refs[ref].uploadFiles.length === 0) {
        // 文件为空时
        return this.$message.warning('尚未选择文件')
      }
      // 1. 获取要上传的文件,raw是一个File对象
      const file = this.$refs[ref].uploadFiles[0].raw
      console.log(file)
      // 判断文件类型
      const symbolIndex = file.name.lastIndexOf('.') // .的下标
      const realType = file.name.substr(symbolIndex + 1) // 文件类型后缀
      if (fileType.indexOf(realType) === -1) {
        this.$refs[ref].uploadFiles = []
        return this.$alert('您选择的文件类型不符合上传要求，请重新选择！', '错误提示', {
          confirmButtonText: '好的，我知道了'
        })
      }
      let fd = new FormData()
      fd.append('file', file)
      // 2. 上传的必备信息
      const tempUploadfileInfo =  JSON.stringify({
        applicationDate: this.editForm.sqrq,
        applicationType: this.editForm.sqtype,
        businessId: this.fileInformation.Busiid,
        businessName: this.fileInformation.BusiName,
        gjjzh: sessionStorage.getItem('gjjzh'),
        ImUUid: this.fileInformation.Imports[index].ImUUid,
        ImportName: this.fileInformation.Imports[index].ImportName,
        FileName: file.name
      })
      fd.append('qtzjFileInfoDTO', new Blob([tempUploadfileInfo], {type: "application/json"}))
      // 3. 调用上传接口
      const { data: res }  = await this.$http.post('/qtzj/uploadFile', fd)
      if (res.code !== 200) {
        this.$message.error(res.msg)
      } else {
        // 更新文件状态
        this.fileInformation.Imports[index].IsUpload = true
      }
    },
    handleExceed() {
      this.$message.warning('只允许上传单个文件！如有调整，请移除文件后重新上传！')
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    // 预览示例
    async preview(index) {
      //  预览前先置空大图预览数组
      this.previewUrlList = []
      const { data: { data: imageInfoList } } = await this.$http.get('/qtzj/downloadFile', {
        params: {
          applicationDate: this.editForm.sqrq,
          applicationType: this.editForm.sqtype,
          gjjzh: sessionStorage.getItem('gjjzh'),
          imUuid: this.fileInformation.Imports[index].ImUUid,
        }
      })
      console.log(imageInfoList)
      // 生成图片前端地址
      // 默认显示的第一张图片
      this.previewUrl = window.URL.createObjectURL(toBlob(imageInfoList[0].FileBase64, imageInfoList[0].FileType, true))
      imageInfoList.forEach(item => {
        let url = window.URL.createObjectURL(toBlob(imageInfoList[0].FileBase64, imageInfoList[0].FileType, true))
        this.previewUrlList.push(url)
      })
      this.previewIsShow = true
    }
  }
}
</script>

<style lang="less" >
  .worker-item .el-form-item__label{
    font-weight: bold;
    font-size: 16px;
  }
  .el-dialog__body {
    padding-top: 0;
  }
  h1 {
    margin-top: 5px;
  }
  .prePic {
    position: fixed;
    top: 40%;
    left: 60%;
    transform: translate(-50%, -50%);
    z-index: 9998;

    &::before {
      content: "提示：单击图片放大";
      display: block;
      text-align: center;
      font-weight: bold;
      color: red;
      background-color: #cfe8fc;
    }

    .el-icon-close {
      border: 2px solid #1e2225;
      font-weight: 700;
      border-radius: 7px;
      position: absolute;
      font-size: 14px;
      top: 1px;
      right: 0;
      cursor: pointer;
    }
    .el-icon-close:hover {
      color: red;
      border: 2px solid red;
    }
  }
</style>
